import React from 'react';
import { Card, Table, Divider ,Modal, Button, Form, Input, Radio, Icon, message ,DatePicker,Pagination ,Upload ,Select,Spin,Popover } from 'antd';
import { NavLink} from 'react-router-dom';
import moment from 'moment';
import ResizeableTitle from './../../../utils/resizeableTitle';
import Utils from './../../../utils/utils';
import './../../../style/style.css';
import { mobileRegex, telRegex,idCardRegex } from '../../../utils/globalConst';
import Axios from "../../../axios";
import axios from 'axios'
import {quickSelectKey} from "../../../config/systemConfig";
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const Option = Select.Option;
const TextArea = Input.TextArea;

export default class JobsManage extends React.Component {
    state = {
        columns: [{
            title: '岗位名称',
            dataIndex: 'name',
            width: 200,
        },{
            title: '所在部门',
            dataIndex: 'deptName',
            width: 150,
        },{
            title: '授权的操作',
            dataIndex: 'authOperation',
            width: 200,
        },{
            title: '授权操作设备',
            dataIndex: 'authEquipment',
            width: 200,
        },{
            title: '描述',
            dataIndex: 'description',
            width: 200,
        },{
            title: '创建时间',
            dataIndex: 'createTime',
            width: 200,
        },{
            title: '操作',
            key: 'action',
            render: (text, record,index) => (
                <span>
                    <a href="javascript:;" onClick={() => this.handleEdit('update',record)} className="btn-txt-primary">更新</a>
                    <Divider type="vertical"/>
                    {record.state=="VALID"?<a href="javascript:;" onClick={() => this.handleUpdateState(record,"DISABLE")} className="btn-txt-danger">禁用</a>:""}
                    {record.state=="DISABLE"?<a href="javascript:;" onClick={() => this.handleUpdateState(record,"VALID")} className="btn-txt-primary">激活</a>:""}
                    <Divider type="vertical"/>
                    <a href="javascript:;" onClick={() => this.handleUpdateState(record,"DELETE")} className="btn-txt-danger">删除</a>
                </span>
            ),
        }],
        editModal:{
            title:'',
            type:'',
            visible: false,
            confirmLoading: false,
        },
    };
    initParams={
        max:10,
        keywords:'',
        page:1,
    }
    componentWillMount(){
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params);
        this.deptRequest();//所有部门请求
    }
    //搜索
    handleFilter = (fieldsValue)=>{
        const values = {
            ...fieldsValue,
        };
        console.log(values);
        this.initParams = {
            ...this.initParams,
            ...values,
            page:1
        }
        let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
        this.listRequest(params)
    }
    //创建or更新 表单
    handleEdit = (type,record)=>{
        let title= '';
        switch (type) {
            case 'create':
                title = '创建岗位';
                break;
            case 'update':
                title = '更新岗位';
                break;
        }
        this.setState({
            editModal:{
                ...this.state.editModal,
                title:title,
                type:type,
                visible:true,
                record,
            }
        })
    }
    //创建or更新 表单提交
    handleEditSubmit = ()=>{
        const _form = this.editForm.props.form;
        _form.validateFields((err, values) => {
            if (err) {
                return;
            }
            console.log(values);
            let params = Utils.FilterParam(values);
            console.log(params)
            if(this.state.editModal.type=='create'){
                this.createRequest(params)
            }else if(this.state.editModal.type=='update'){
                this.updateRequest(params)
            }
        });
    }
    //取消 创建or更新
    handleEditCancle = ()=>{
        const _form = this.editForm.props.form;
        this.setState({
            editModal:{
                ...this.state.editModal,
                visible:false
            }
        },()=>{
            _form.resetFields();
        })
    }
    //更新状态
    handleUpdateState = (record,targetState)=>{
        console.log(record)
        console.log(targetState)
        let stateTxt = "";
        switch (targetState){
            case "VALID":
                stateTxt="激活";
                break;
            case "DISABLE":
                stateTxt="禁用";
                break;
            case "DELETE":
                stateTxt="删除";
                break;

        }
        let params = {
            id:record.id,
            state :targetState,
        }
        Modal.confirm({
            title: `确认${stateTxt}`,
            content: <div>
                {targetState=="VALID"?<div className="txt-danger">确定激活岗位？</div>:""}
                {targetState=="DISABLE"?<div className="txt-danger">确定禁用岗位？</div>:""}
                {targetState=="DELETE"?<div className="txt-danger">确定删除岗位？删除后数据不可恢复</div>:""}
            </div>,
            okText:'确认',
            cancelText:'取消',
            onOk:()=>{
                this.updateStateRequest(params);
            }
        })
        //this.updateStateRequest(params)
    }
    /*岗位列表  请求*/
    listRequest = (params)=>{
        let _this = this;
        this.setState({
            loading:true,
            loadingTxt:'加载中...'
        })
        Axios.dataRequest({
            block:'/hr',
            url:'/jobs',
            params:params,
        }).then((data)=>{
            console.log(data)
            let page = data.page;
            let dataSource = data.data;
            dataSource.map((item)=>{
                item.key = item.id;
                return item;
            })
            this.setState({
                loading:false,
                dataSource,
                pagination: Utils.pagination(page, (current) => {
                    _this.initParams.page = current;
                    let params = this.initParams;
                    _this.listRequest(params);
                },(current,pageSize) =>{
                    _this.initParams.page = current;
                    _this.initParams.max = pageSize;
                    let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                    _this.listRequest(params);
                })
            })
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    /*岗位创建 请求*/
    createRequest = (params)=>{
        this.setState({
            editModal:{
                ...this.state.editModal,
                confirmLoading: true,
            }
        })
        Axios.formRequest({
            block:'/hr',
            url:'/jobs',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                editModal:{
                    ...this.state.editModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('创建成功！',2,()=>{
                    //this.listRequest(_this.initParams);
                    window.location.reload()
                });
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                editModal:{
                    ...this.state.editModal,
                    visible: false,
                    confirmLoading: false,
                }
            })
        })
    }
   /* 岗位更新 请求*/
    updateRequest = (params)=>{
        this.setState({
            editModal:{
                ...this.state.editModal,
                confirmLoading: true,
            }
        })
        Axios.formPutRequest({
            block:'/hr',
            url:'/jobs',
            params:params,
        }).then((data)=>{
            console.log(data)
            this.setState({
                editModal:{
                    ...this.state.editModal,
                    visible: false,
                    confirmLoading: false,
                }
            },()=>{
                message.success('更新成功！',2,()=>{
                    //this.listRequest(_this.initParams);
                    window.location.reload()
                });
            })
        }).catch((error)=>{
            console.log(error);
            this.setState({
                editModal:{
                    ...this.state.editModal,
                    editModal: false,
                }
            })
        })
    }
    /*岗位状态更新*/
    updateStateRequest = (params)=>{
        let stateTxt = "";
        switch (params.state){
            case "VALID":
                stateTxt="激活";
                break;
            case "DISABLE":
                stateTxt="禁用";
                break;
            case "DELETE":
                stateTxt="删除";
                break;

        }
        this.setState({
            loading:true,
            loadingTxt:stateTxt+'中...'
        })
        Axios.formRequest({
            block:'/hr',
            url:'/jobs/updateState',
            params:params,
        }).then((data)=>{
            console.log(data);
            this.setState({ loading:false })
            message.success(stateTxt+'成功！',2,()=>{
                let params = Utils.FilterParam(this.initParams); //过滤掉为空的参数
                this.listRequest(params)
            });
        }).catch((error)=>{
            this.setState({ loading:false })
            console.log(error);
        })
    }
    /*所有部门请求*/
    deptRequest = ()=>{
        Axios.dataRequest({
            block:'/hr',
            url:'/department',
            params:"",
        }).then((data)=>{
            console.log(data)
            let depts = data.data;
            this.setState({
                depts,
            })
        }).catch((error)=>{
            console.log(error);
        })
    }
    //伸缩列
    components = {
        header: {
            cell:ResizeableTitle
        },
    };
    handleResize = index => (e, { size }) => {
        this.setState(({ columns }) => {
            const nextColumns = [...columns];
            nextColumns[index] = {
                ...nextColumns[index],
                width: size.width,
            };
            return { columns: nextColumns };
        });
    };
    render() {
        const columns = this.state.columns.map((col, index) => ({
            ...col,
            onHeaderCell: column => ({
                width: column.width,
                onResize: this.handleResize(index),
            }),
        }));
        const depts = this.state.depts||[];
        return (
            <div className="tab-list-box">
                <Spin spinning={this.state.loading} size="large" tip={this.state.loadingTxt}>
                    <Card
                        title="岗位列表"
                        bordered={false}>
                        <div style={{textAlign:'right',marginBottom:15}}>
                            <div className="filter-box" style={{marginBottom:15}}>
                                <FilterForm filterSubmit={(fieldsValue)=>{this.handleFilter(fieldsValue)}}/>
                                <Button type="primary" icon="plus" onClick={()=>this.handleEdit('create')}>创建岗位</Button>
                            </div>
                        </div>
                        <Table
                            bordered
                            components={this.components}
                            columns={columns}
                            dataSource={this.state.dataSource}
                            pagination={this.state.pagination}
                        />
                    </Card>
                </Spin>
                <Modal title={this.state.editModal.title}
                       visible={this.state.editModal.visible}
                       onOk={this.handleEditSubmit}
                       okText="提交"
                       confirmLoading={this.state.editModal.confirmLoading}
                       onCancel={this.handleEditCancle}
                >
                    <EditForm
                        record={this.state.editModal.record}
                        depts={depts}
                        wrappedComponentRef={(editForm)=>{this.editForm = editForm;}}/>
                </Modal>
            </div>
        );
    }

}
//创建、更新岗位表单
class EditForm extends React.Component{
    state = {}
    render(){
        const { getFieldDecorator } = this.props.form;
        const formItemLayout = {
            labelCol: {span: 6},
            wrapperCol: {span: 16}
        };
        const record = this.props.record || {};
        const depts = this.props.depts;
        const deptOptions = depts.map((item,index)=>{
            return <Option key={item.id} value={item.id}>{item.name}</Option>
        })
        return (
            <Form>
                <FormItem label="id" {...formItemLayout} style={{display:'none'}}>
                    {
                        getFieldDecorator('id',{
                            initialValue:record.id
                        })(
                            <Input type="hidden"/>
                        )
                    }
                </FormItem>
                <FormItem label="岗位所在部门" {...formItemLayout}>
                    {
                        getFieldDecorator('deptId',{
                            rules: [{ required: true, message: '请选择岗位所在部门!' }],
                            initialValue:record.deptId
                        })(
                            <Select
                                placeholder="岗位所在部门"
                                style={{minWidth: 160}}
                                showSearch
                                optionFilterProp="children"
                                filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                            >
                                {deptOptions}
                            </Select>
                        )
                    }
                </FormItem>
                <FormItem label="岗位名称" {...formItemLayout}>
                    {
                        getFieldDecorator('name',{
                            rules: [{ required: true, message: '请填写岗位名称!' }],
                            initialValue:record.name
                        })(
                            <Input type="text" placeholder="岗位名称"/>
                        )
                    }
                </FormItem>
                <FormItem label="授权的操作" {...formItemLayout}>
                    {
                        getFieldDecorator('authOperation',{
                            rules: [{ required: true, message: '请填写授权的操作!' }],
                            initialValue:record.authOperation
                        })(
                            <TextArea placeholder="授权的操作（例如：百菌清、三唑酮）" autosize/>
                        )
                    }
                </FormItem>
                <FormItem label="授权操作设备" {...formItemLayout}>
                    {
                        getFieldDecorator('authEquipment',{
                            rules: [{ required: true, message: '请填写授权操作设备!' }],
                            initialValue:record.authEquipment
                        })(
                            <TextArea placeholder="授权操作设备（例如：PE气相色谱仪【580】）" autosize/>
                        )
                    }
                </FormItem>
                <FormItem label="描述" {...formItemLayout}>
                    {
                        getFieldDecorator('description',{
                            initialValue:record.description
                        })(
                            <TextArea type="text" placeholder="描述" autosize/>
                        )
                    }
                </FormItem>
            </Form>
        );
    }
}
EditForm = Form.create({})(EditForm);
//搜索表单
class FilterForm extends React.Component{
    handleFilterSubmit = ()=>{
        let fieldsValue = this.props.form.getFieldsValue();
        this.props.filterSubmit(fieldsValue);
    }
    //重置
    reset = ()=>{
        this.props.form.resetFields();
    }
    render(){
        const { getFieldDecorator } = this.props.form;
        return (
            <Form layout="inline">
                <FormItem label="关键词">
                    {
                        getFieldDecorator('keywords',{
                        })(
                            <Input type="text" placeholder="关键词"/>
                        )
                    }
                </FormItem>
                <FormItem>
                    <Button type="primary" style={{margin:'0 20px'}} onClick={this.handleFilterSubmit}>查询</Button>
                    <Button onClick={this.reset}>重置</Button>
                </FormItem>
            </Form>
        );
    }
}
FilterForm = Form.create({})(FilterForm);